
package poker;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import prop.Carta;
import prop.Configuracion;
import prop.DriverDomainRanking;

public class Ventana extends javax.swing.JFrame implements Serializable {
    private DriverDomainRanking rankGeneral,rankSesion;
    private DriverDomainInterfaz driver;
    private Configuracion conf;

    public Ventana(DriverDomainInterfaz driv, DriverDomainRanking rankGral,Configuracion conf) {
        driver = driv;
        rankGeneral = rankGral;
        this.conf = conf;
        initComponents();
        this.setVisible(true);
        setAreaDibujo(new AreaDibujoNada());
        setJugando(false);
    }

    public void setJugando(boolean t) {
        menuConfig.setVisible(!t);
        menuRankingSesion.setVisible(t);
    }

    public void anadirLog(String s) {
        areaLogText.setText(areaLogText.getText() + s + "\n");
    }

    public void setLog(String s) {
        areaLogText.setText(s);
    }

    public void iniciarDescarte(Vector<Carta> vect, String nombreJugador) {
        setAreaDibujo(new AreaDibujoDescarte(this, vect, nombreJugador));
    }

    public void finalizarDescarte(Vector vect) {
        setAreaDibujo(new AreaDibujoNada());
        driver.finalizarDescarte(vect);
    }

    public void iniciarEspera(String s) {
        setAreaDibujo(new AreaDibujoEspera(s, this));
    }

    public void finalizarEspera() {
        setAreaDibujo(new AreaDibujoNada());
        driver.finalizarEspera();
    }

    public void iniciarApuesta(String nombreJug, int dineroJug, int apuestaMesa, Vector cartas) {
        setAreaDibujo(new AreaDibujoApuesta(this, nombreJug, dineroJug, apuestaMesa, cartas));
    }

    public void finalizarApuesta(int apuestaFinal) {
        setAreaDibujo(new AreaDibujoNada());
        driver.finalizarApuesta(apuestaFinal);
    }

    public void iniciarGanaPartida(String jug, String din) {
        Vector<String> v = new Vector<String>();
        v.add(jug);
        setAreaDibujo(new AreaDibujoGanaPartida(v, din, this));
    }

    public void iniciarGanaPartida(Vector<String> v, String din) {
        setAreaDibujo(new AreaDibujoGanaPartida(v, din, this));
    }

    public void iniciarGanaSesion(Vector<String> v, String din) {
        setAreaDibujo(new AreaDibujoGanaSesion(v, din, this));
    }

    public void finalizarGanaSesion() {
        setAreaDibujo(new AreaDibujoNada());
        driver.finalizarGanaSesion();
    }

    public void finalizarGanaPartida() {
        setAreaDibujo(new AreaDibujoNada());
        driver.finalizarGanaPartida();
    }

    public void guardarConf() {
        driver.guardarConf("config.cnf", conf);
    }

    private void setAreaDibujo(AreaDibujo area) {
        if (areaDibujo != null) getContentPane().remove(areaDibujo);
        areaDibujo = area;
        areaDibujo.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                areaDibujoMouseClicked(evt);
            }
        });
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(areaDibujo, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(areaLog, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(areaDibujo, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(areaLog, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
        );

        pack();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        areaDibujo = new poker.AreaDibujo();
        areaLog = new javax.swing.JScrollPane();
        areaLogText = new javax.swing.JTextArea();
        barraMenu = new javax.swing.JMenuBar();
        menuJuego = new javax.swing.JMenu();
        menuJuegoNuevo = new javax.swing.JMenuItem();
        menuCargarSesion = new javax.swing.JMenuItem();
        menuRanking = new javax.swing.JMenu();
        menuRankingGeneral = new javax.swing.JMenuItem();
        menuRankingSesion = new javax.swing.JMenuItem();
        menuConfig = new javax.swing.JMenu();
        jMenu1 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setName("ventanaPrincipal"); // NOI18N
        setResizable(false);

        areaDibujo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                areaDibujoMouseClicked(evt);
            }
        });

        areaLogText.setColumns(20);
        areaLogText.setEditable(false);
        areaLogText.setRows(5);
        areaLog.setViewportView(areaLogText);

        menuJuego.setLabel("Juego");

        menuJuegoNuevo.setText("Nueva Sesion");
        menuJuegoNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuJuegoNuevoActionPerformed(evt);
            }
        });
        menuJuego.add(menuJuegoNuevo);

        menuCargarSesion.setText("Cargar Sesion");
        menuCargarSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuCargarSesionActionPerformed(evt);
            }
        });
        menuJuego.add(menuCargarSesion);

        barraMenu.add(menuJuego);

        menuRanking.setLabel("Ranking");

        menuRankingGeneral.setText("General");
        menuRankingGeneral.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuRankingGeneralActionPerformed(evt);
            }
        });
        menuRanking.add(menuRankingGeneral);

        menuRankingSesion.setText("Sesion");
        menuRankingSesion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuRankingSesionActionPerformed(evt);
            }
        });
        menuRanking.add(menuRankingSesion);

        barraMenu.add(menuRanking);
        menuRanking.getAccessibleContext().setAccessibleName(null);

        menuConfig.setText("Configuracion");
        menuConfig.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuConfigMouseClicked(evt);
            }
        });
        barraMenu.add(menuConfig);

        jMenu1.setText("Ayuda");
        jMenu1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jMenu1MouseClicked(evt);
            }
        });
        barraMenu.add(jMenu1);

        setJMenuBar(barraMenu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(areaDibujo, javax.swing.GroupLayout.PREFERRED_SIZE, 640, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(areaLog, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(areaDibujo, javax.swing.GroupLayout.PREFERRED_SIZE, 480, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(areaLog, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void menuRankingGeneralActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuRankingGeneralActionPerformed
        new VentanaRanking(rankGeneral, this);
}//GEN-LAST:event_menuRankingGeneralActionPerformed

    private void menuRankingSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuRankingSesionActionPerformed
        new VentanaRanking(driver.getSistema().getDDR2(), this);
    }//GEN-LAST:event_menuRankingSesionActionPerformed

    private void areaDibujoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_areaDibujoMouseClicked
        areaDibujo.clickRecibido(evt.getX(), evt.getY());
    }//GEN-LAST:event_areaDibujoMouseClicked

    private void menuCargarSesionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuCargarSesionActionPerformed
        String s = JOptionPane.showInputDialog("Nombre de la sesion:");
        driver.cargarSesion(s + ".ses");
}//GEN-LAST:event_menuCargarSesionActionPerformed

    private void menuJuegoNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuJuegoNuevoActionPerformed
        new VentanaNuevaSesion(this, conf, driver);
}//GEN-LAST:event_menuJuegoNuevoActionPerformed

    private void menuConfigMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuConfigMouseClicked
        new VentanaConfiguracion(conf, this);
    }//GEN-LAST:event_menuConfigMouseClicked

    private void jMenu1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jMenu1MouseClicked
        try {
            // la ruta hasta el directorio donde se encuentra el programa es (termina en /): Main.rutaProg
            String urlAyuda = Main.rutaProg + "guia" + File.separator + "index.html";
            
            String so = System.getProperty("os.name");
            if (so.startsWith("Mac OS")) {
                try {
                    Class mng = Class.forName("com.apple.eio.FileManager");
                    Method ourl = mng.getDeclaredMethod("openURL", new Class[]{String.class});
                    ourl.invoke(null, new Object[]{urlAyuda});
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                } catch (NoSuchMethodException ex) {
                    Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SecurityException ex) {
                    Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (so.startsWith("Windows")) {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + urlAyuda);
            } else {
                String[] navs = {"firefox", "konqueror", "mozilla", "opera", "netscape"};
                String nav = null;
                for (int i = 0; i < navs.length && nav == null; ++i) {
                    try {
                        if (Runtime.getRuntime().exec(new String[]{"which", navs[i]}).waitFor() == 0) {
                            nav = navs[i];
                        }
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                if (nav != null) {
                    Runtime.getRuntime().exec(new String[]{nav, urlAyuda});
                }
            }
        } catch (IOException ex) {
            Logger.getLogger(Ventana.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jMenu1MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private poker.AreaDibujo areaDibujo;
    private javax.swing.JScrollPane areaLog;
    private javax.swing.JTextArea areaLogText;
    private javax.swing.JMenuBar barraMenu;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem menuCargarSesion;
    private javax.swing.JMenu menuConfig;
    private javax.swing.JMenu menuJuego;
    private javax.swing.JMenuItem menuJuegoNuevo;
    private javax.swing.JMenu menuRanking;
    private javax.swing.JMenuItem menuRankingGeneral;
    private javax.swing.JMenuItem menuRankingSesion;
    // End of variables declaration//GEN-END:variables

}
